package portal.bean;

import java.io.IOException;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;

import javax.faces.application.Application;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oracle.adf.view.rich.component.rich.input.RichInputText;
import oracle.adf.view.rich.component.rich.input.RichSelectManyShuttle;
import oracle.adf.view.rich.component.rich.input.RichSelectOneRadio;
import oracle.adf.view.rich.component.rich.layout.RichPanelBorderLayout;

import oracle.adf.view.rich.component.rich.nav.RichCommandLink;
import oracle.adf.view.rich.component.rich.output.RichOutputText;

import oracle.adf.view.rich.context.AdfFacesContext;

import oracle.stellent.ridc.IdcClient;
import oracle.stellent.ridc.IdcContext;
import oracle.stellent.ridc.model.DataBinder;
import oracle.stellent.ridc.model.DataObject;
import oracle.stellent.ridc.model.DataResultSet;

import oracle.stellent.ridc.protocol.ServiceResponse;

import oracle.webcenter.doclib.internal.model.presenter.conf.SearchCriterion;
import oracle.webcenter.doclib.internal.model.presenter.conf.SortCriterion;

import oracle.webcenter.framework.view.JSFUtils;
import oracle.webcenter.navigationframework.NavigationResource;
import oracle.webcenter.portalframework.sitestructure.SiteStructure;

import org.apache.myfaces.trinidadinternal.taglib.util.MethodExpressionMethodBinding;

import portal.Global;
import portal.UtilsContent;

public class SearchBean {
    private RichPanelBorderLayout pagingPanel = new RichPanelBorderLayout();
    private String detailUrl;
    private RichInputText txtNoidung;
    private RichSelectOneRadio radioTiemkiemketqua;
    private List<SelectItem> lstChuyenmuc = new ArrayList<SelectItem>();
    private List<DataObject> lstResult = new ArrayList<DataObject>();
    private RichSelectManyShuttle selectManyShuttleChuyenmuc;
    private List<String> lstChuyenmucLuaChon = new ArrayList<String>();
    private Date tungay;
    private Date denngay;
    private String noidung;
    private String kqTimkiem = "1";
    private int currentPage = 1;
    private int selectedPage = 1;
    private int numberOfPage = -1;
    private int numberOfResult = 0;
    private String totalRows = "0";
    private boolean hasnextpage;
    private String individualpagedetailUrl;
    private RichInputText inputDetailPath;
    private String searchPram;
    private String searchUrl;
    private RichInputText inputTextSearch;
    private String initPram="";

    public SearchBean() {
        super();
    }

    private void loadChuyenmuc() {
        DataResultSet rs =
            UtilsContent.getViewInfor("CHUYENMUCTIN_VIEW", "CHUYENMUCTIN",
                                      Global.getIdcClient(),
                                      Global.getUserContext());
        List<DataObject> lstObj = rs.getRows();
        for (DataObject obj : lstObj) {
            if (obj.get("NGONNGU").toString().equals(LocaleBean.getCurrentInstance().getLanguage())) {
                SelectItem item = new SelectItem();
                item.setLabel(obj.get("CHUYENMUC"));
                item.setValue(obj.get("ID"));
                lstChuyenmuc.add(item);
            }
        }
    }

    /**
     * @creator
     * @comment Thu tuc tim kiem noi dung trong UCM
     * @param queryString
     * @param sortField
     * @param numberofResult 0: is not set
     * @param startRow 0: is not set
     * @param endRow 0: is not set
     * @param sortOrder ASC, DESC
     * @param client
     * @param userContext
     * @return
     */
    private DataResultSet SearchUCMContent(String queryString,
                                           String sortField,
                                           int numberofResult, int startRow,
                                           int endRow, String sortOrder,
                                           IdcClient client,
                                           IdcContext userContext) {
        DataResultSet obj = null;
        try {
            DataBinder dataBinder = client.createBinder();
            dataBinder.putLocal("IdcService", "GET_SEARCH_RESULTS");
            dataBinder.putLocal("QueryText", queryString);
            dataBinder.putLocal("SortField", sortField);
            dataBinder.putLocal("PageNumber", Integer.toString(selectedPage));
            if (numberofResult > 0)
                dataBinder.putLocal("ResultCount",
                                    Integer.toString(numberOfResult));
            if (startRow > 0)
                dataBinder.putLocal("StartRow", String.valueOf(startRow));
            if (endRow > 0)
                dataBinder.putLocal("EndRow", String.valueOf(endRow));
            if (sortOrder != null && sortOrder.length() > 0)
                dataBinder.putLocal("SortOrder", sortOrder);
            ServiceResponse ridc_response;
            ridc_response = client.sendRequest(userContext, dataBinder);
            DataBinder binder = ridc_response.getResponseAsBinder();
            totalRows = binder.getLocal("TotalRows");
            obj = binder.getResultSet("SearchResults");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return obj;
    }

    /**
     * @creator
     * @comment
     * @param tungay
     * @param denngay
     * @param noidung
     * @param lstchuyenmuc
     * @param ngonnguid
     * @return
     */
    private String createQuery(Date tungay, Date denngay, String noidung,
                               List<String> lstchuyenmuc, String ngonnguid) {
        String queryString =
            "(dDocType <contains> `Tinbai`) <AND> xmHienthi <contains> `True` <AND> xmNgayxuatban <= `<$dateCurrent(0)$>`";
        if (tungay != null && denngay != null) {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            queryString +=
                    " <AND> xmNgayxuatban >= `" + df.format(tungay) + "`";
            queryString +=
                    " <AND> xmNgayxuatban <= `" + df.format(denngay) + "`";
        } else if ((tungay != null && denngay == null)) {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            queryString +=
                    " <AND> xmNgayxuatban >= `" + df.format(tungay) + "`";
        } else if (tungay == null && denngay != null) {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            queryString +=
                    " <AND> xmNgayxuatban <= `" + df.format(denngay) + "`";
        }
        if (noidung != null && !noidung.equals("")) {
            noidung = noidung.trim();
            noidung = noidung.toLowerCase().replaceAll("<ftx>", "");
            noidung = noidung.toLowerCase().replaceAll("</ftx>", "");
            while (noidung.contains("  "))
                noidung = noidung.replaceAll("  ", " ");
            txtNoidung.setValue(noidung);
            if (kqTimkiem.equals("0")) {
                String[] temp = noidung.split(" ");
                String nd = "";
                if (temp != null && temp.length > 1) {
                    for (String s : temp) {
                        nd += s + ",";
                    }
                }
                if (nd.length() > 0)
                    queryString += " <AND> (<ftx>" + nd + "</ftx>)";
            } else {
                queryString += " <AND> (<ftx>" + noidung + "</ftx>)";
            }


        }
        if (lstchuyenmuc != null && lstchuyenmuc.size() > 0) {
            queryString += " <AND> (";
            for (String chuyenmuc : lstchuyenmuc)
                queryString +=
                        " xmChuyenmuctin <contains> `" + chuyenmuc + "` <OR> xmMuctinhienthi <contains> `" +
                        chuyenmuc + "` <OR> ";
            queryString =
                    queryString.substring(0, queryString.lastIndexOf("<OR>"));
            queryString += ")";
        }
        queryString += " <AND> xmNgonngu <matches> `" + ngonnguid + "`";
        return queryString;
    }

    /**
     * @creator TuyenNT
     * @comment thu tuc phan trang tin tuc
     * @param selectedPage
     */
    private void getListNewsByKieutinWithPaging(int selectedPage) {

        int startRow = 1;
        try {
            String expression = "#{nodes}";

            numberOfResult = 20;
            if (numberOfResult > 0) {
                String chuyenmuc;
                if (txtNoidung.getValue() != null)
                    noidung = txtNoidung.getValue().toString();
                else
                    noidung = "";
                String querystring =
                    createQuery(tungay, denngay, noidung, lstChuyenmucLuaChon,
                                LocaleBean.getCurrentInstance().getLanguage());
                startRow = numberOfResult * (selectedPage - 1) + 1;
                DataResultSet drs =
                    SearchUCMContent(querystring, "xmNgayxuatban",
                                     numberOfResult, startRow, 0, "DESC",
                                     Global.getIdcClient(),
                                     Global.getUserContext());
                lstResult = drs.getRows();
                int rowscount = 0;
                if (!totalRows.equals("0")) {
                    rowscount = Integer.parseInt(totalRows);
                    numberOfPage =
                            rowscount % numberOfResult > 0 ? (rowscount /
                                                              numberOfResult +
                                                              1) :
                            rowscount / numberOfResult;

                    if (pagingPanel.getChildCount() > 0)
                        pagingPanel.getChildren().clear();

                    generatePrevLink(selectedPage);
                    if (numberOfPage >= 5) {
                        if (selectedPage < numberOfPage)
                            hasnextpage = true;
                        if (selectedPage - 2 >= 0 &&
                            selectedPage + 2 <= numberOfPage) {
                            if (selectedPage - 2 > 1) {
                                generateDots("...");

                            }
                            if (selectedPage > 2) {
                                generatePagenumber(selectedPage - 2);

                            }
                            generatePagenumber(selectedPage - 1);
                            generatePagenumber(selectedPage);
                            generatePagenumber(selectedPage + 1);
                            generatePagenumber(selectedPage + 2);

                            if (selectedPage + 2 < 5) {
                                generatePagenumber(selectedPage + 3);
                            }
                            if (selectedPage + 2 < numberOfPage) {
                                generateDots("...");
                            }

                        } else if (selectedPage < 2) {
                            for (int i = selectedPage; i <= selectedPage + 4;
                                 i++) {
                                generatePagenumber(i);
                            }
                            generateDots("...");

                        } else if (selectedPage + 2 > numberOfPage) {
                            generateDots("...");
                            if (selectedPage == numberOfPage)
                                for (int i = selectedPage - 4;
                                     i <= selectedPage; i++) {
                                    generatePagenumber(i);
                                }
                            else
                                for (int i = selectedPage - 3;
                                     i <= selectedPage + 1; i++) {
                                    generatePagenumber(i);
                                }
                        }
                    } else {
                        for (int i = 1; i <= numberOfPage; i++) {
                            generatePagenumber(i);
                        }
                        hasnextpage = false;
                    }
                } else
                    hasnextpage = false;
                generateNextLink(selectedPage);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * @creator
     * @comment
     * @param currentpage
     */
    public void generatePrevLink(int currentpage) {
        FacesContext fc = FacesContext.getCurrentInstance();
        Application app = fc.getApplication();
        ExpressionFactory elFactory = app.getExpressionFactory();
        ELContext elContext = fc.getELContext();
        MethodExpression methodExpression =
            elFactory.createMethodExpression(elContext,
                                             "#{searchBean.prevPage}", null,
                                             new Class[] { ActionEvent.class });
        MethodExpressionMethodBinding methodExpressionMethodBinding =
            new MethodExpressionMethodBinding(methodExpression);
        RichCommandLink commandLink = new RichCommandLink();
        //commandLink.setPartialSubmit(true);
        commandLink.setText("« Trước");
        commandLink.getAttributes().put("actionListener",
                                        methodExpressionMethodBinding);
        commandLink.getAttributes().put("prevpage", currentpage - 1);
        commandLink.setInlineStyle("margin-right:5px;");
        if (currentpage < 2)
            commandLink.setDisabled(true);
        else
            commandLink.setDisabled(false);
        pagingPanel.getChildren().add(commandLink);
    }

    /**
     * @creator
     * @comment
     * @param currentpage
     */
    public void generateNextLink(int currentpage) {
        FacesContext fc = FacesContext.getCurrentInstance();
        Application app = fc.getApplication();
        ExpressionFactory elFactory = app.getExpressionFactory();
        ELContext elContext = fc.getELContext();
        MethodExpression methodExpression =
            elFactory.createMethodExpression(elContext,
                                             "#{searchBean.nextPage}", null,
                                             new Class[] { ActionEvent.class });
        MethodExpressionMethodBinding methodExpressionMethodBinding =
            new MethodExpressionMethodBinding(methodExpression);
        RichCommandLink commandLink = new RichCommandLink();
        //commandLink.setPartialSubmit(true);
        commandLink.setText("Sau »");
        commandLink.getAttributes().put("actionListener",
                                        methodExpressionMethodBinding);
        commandLink.getAttributes().put("nexpage", currentpage + 1);
        commandLink.setInlineStyle("margin-left:5px;");
        if (!hasnextpage)
            commandLink.setDisabled(true);
        pagingPanel.getChildren().add(commandLink);
    }

    /**
     * @creator
     * @comment
     * @param pagenumber
     */
    public void generatePagenumber(int pagenumber) {
        FacesContext fc = FacesContext.getCurrentInstance();
        Application app = fc.getApplication();
        ExpressionFactory elFactory = app.getExpressionFactory();
        ELContext elContext = fc.getELContext();
        MethodExpression methodExpression =
            elFactory.createMethodExpression(elContext,
                                             "#{searchBean.pageSeleted}", null,
                                             new Class[] { ActionEvent.class });
        MethodExpressionMethodBinding methodExpressionMethodBinding =
            new MethodExpressionMethodBinding(methodExpression);
        RichCommandLink commandLink = new RichCommandLink();
        //commandLink.setPartialSubmit(true);
        commandLink.setText(String.valueOf(pagenumber));
        if (pagenumber == selectedPage)
            commandLink.setInlineStyle("font-weight:bold; margin:0 2px;");
        else
            commandLink.setInlineStyle("margin:0 2px;");

        //commandLink.setActionExpression(methodExpression);
        commandLink.getAttributes().put("actionListener",
                                        methodExpressionMethodBinding);
        commandLink.getAttributes().put("selectedpage", pagenumber);
        pagingPanel.getChildren().add(commandLink);
    }

    /**
     * @creator
     * @comment
     * @param value
     */
    public void generateDots(String value) {
        FacesContext fc = FacesContext.getCurrentInstance();
        Application app = fc.getApplication();
        ExpressionFactory elFactory = app.getExpressionFactory();
        ELContext elContext = fc.getELContext();
        RichOutputText ouputtext = new RichOutputText();
        ouputtext.setValue(value);
        pagingPanel.getChildren().add(ouputtext);
    }

    /**
     * @comment lay url cua trang hien thi chi tiet noi dung
     * @return
     */
    private String detailPageUrl() {
        String pageurl = "";
        String elexp = "#{navigationContext.defaultNavigationModel}";
        SiteStructure str = (SiteStructure)JSFUtils.resolveExpression(elexp);
        List<NavigationResource> lstnavresources;
        try {
            if (inputDetailPath != null &&
                inputDetailPath.getValue() != null) {
                String strparentpath = inputDetailPath.getValue().toString();
                //elexp = "#{node.propertyMap['xmChuyenmuctin'].value}";
                //Object obj = (Object)JSFUtils.resolveExpression(elexp);
                String strChuyenmuc =
                    strparentpath.substring(strparentpath.lastIndexOf("/") + 1,
                                            strparentpath.length());
                strparentpath =
                        strparentpath.substring(0, strparentpath.lastIndexOf("/"));
                lstnavresources = str.getResource(strparentpath).getChildren();
                for (NavigationResource nav1 : lstnavresources) {
                    for (NavigationResource nav2 : nav1.getChildren()) {
                        if (nav2.getChildCount() > 0) {
                            for (NavigationResource nav3 :
                                 nav2.getChildren()) {
                                if (nav3.getChildCount() > 0) {
                                    for (NavigationResource nav4 :
                                         nav3.getChildren()) {
                                        if (nav4.getChildCount() > 0) {
                                            for (NavigationResource nav5 :
                                                 nav4.getChildren()) {
                                                if (nav5.getPrettyUrl().contains(strChuyenmuc)) {
                                                    pageurl =
                                                            nav5.getPrettyUrl();
                                                    break;
                                                }
                                            }
                                        } else {
                                            if (nav4.getPrettyUrl().contains(strChuyenmuc)) {
                                                pageurl = nav4.getPrettyUrl();
                                                break;
                                            }
                                        }
                                        if (pageurl.length() > 0)
                                            break;

                                    }
                                } else {
                                    if (nav3.getPrettyUrl().contains(strChuyenmuc)) {
                                        pageurl = nav3.getPrettyUrl();
                                        break;
                                    }
                                }

                                if (pageurl.length() > 0)
                                    break;
                            }
                        } else {

                            if (nav2.getPrettyUrl().contains(strChuyenmuc)) {
                                pageurl = nav2.getPrettyUrl();
                                break;
                            }
                        }
                        if (pageurl.length() > 0)
                            break;
                    }
                    if (pageurl.length() > 0)
                        break;
                }
            }
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }
        return pageurl;

    }

    public void prevPage(ActionEvent actionEvent) {
        selectedPage =
                Integer.parseInt(actionEvent.getComponent().getAttributes().get("prevpage").toString());
        getListNewsByKieutinWithPaging(selectedPage);
        //AdfFacesContext.getCurrentInstance().addPartialTarget(vbckTable);
        AdfFacesContext.getCurrentInstance().addPartialTarget(pagingPanel);
    }

    public void pageSeleted(ActionEvent actionEvent) {
        selectedPage =
                Integer.parseInt(actionEvent.getComponent().getAttributes().get("selectedpage").toString());
        getListNewsByKieutinWithPaging(selectedPage);
        //AdfFacesContext.getCurrentInstance().addPartialTarget(vbckTable);
        AdfFacesContext.getCurrentInstance().addPartialTarget(pagingPanel);
    }

    public void nextPage(ActionEvent actionEvent) {
        selectedPage =
                Integer.parseInt(actionEvent.getComponent().getAttributes().get("nexpage").toString());
        getListNewsByKieutinWithPaging(selectedPage);
        //        AdfFacesContext.getCurrentInstance().addPartialTarget(vbckTable);
        AdfFacesContext.getCurrentInstance().addPartialTarget(pagingPanel);
    }

    public void setPagingPanel(RichPanelBorderLayout pagingPanel) {
        this.pagingPanel = pagingPanel;
    }

    public RichPanelBorderLayout getPagingPanel() {
        return pagingPanel;
    }

    public void setDetailUrl(String detailUrl) {
        this.detailUrl = detailUrl;
    }

    public String getDetailUrl() {
        return detailUrl;
    }

    public String SearchingAction() {
        // Add event code here...
        getListNewsByKieutinWithPaging(1);
        return null;
    }

    public void setTxtNoidung(RichInputText txtNoidung) {
        this.txtNoidung = txtNoidung;
    }

    public RichInputText getTxtNoidung() {
        return txtNoidung;
    }

    public void setRadioTiemkiemketqua(RichSelectOneRadio radioTiemkiemketqua) {
        this.radioTiemkiemketqua = radioTiemkiemketqua;
    }

    public RichSelectOneRadio getRadioTiemkiemketqua() {
        return radioTiemkiemketqua;
    }

    public void setLstChuyenmuc(List<SelectItem> lstChuyenmuc) {
        this.lstChuyenmuc = lstChuyenmuc;
    }

    public List<SelectItem> getLstChuyenmuc() {
        loadChuyenmuc();
        return lstChuyenmuc;
    }

    public void setLstResult(List<DataObject> lstResult) {
        this.lstResult = lstResult;
    }

    public List<DataObject> getLstResult() {
        return lstResult;
    }

    public void setSelectManyShuttleChuyenmuc(RichSelectManyShuttle selectManyShuttleChuyenmuc) {
        this.selectManyShuttleChuyenmuc = selectManyShuttleChuyenmuc;
    }

    public RichSelectManyShuttle getSelectManyShuttleChuyenmuc() {
        return selectManyShuttleChuyenmuc;
    }

    public void setLstChuyenmucLuaChon(List<String> lstChuyenmucLuaChon) {
        this.lstChuyenmucLuaChon = lstChuyenmucLuaChon;
    }

    public List<String> getLstChuyenmucLuaChon() {
        return lstChuyenmucLuaChon;
    }

    public void setTungay(Date tungay) {
        this.tungay = tungay;
    }

    public Date getTungay() {
        return tungay;
    }

    public void setDenngay(Date denngay) {
        this.denngay = denngay;
    }

    public Date getDenngay() {
        return denngay;
    }

    public void setNoidung(String noidung) {
        this.noidung = noidung;
    }

    public String getNoidung() {
        return noidung;
    }

    public void setKqTimkiem(String kqTimkiem) {
        this.kqTimkiem = kqTimkiem;
    }

    public String getKqTimkiem() {
        return kqTimkiem;
    }

    public void setIndividualpagedetailUrl(String individualpagedetailUrl) {
        this.individualpagedetailUrl = individualpagedetailUrl;
    }

    public String getIndividualpagedetailUrl() {
        individualpagedetailUrl = detailPageUrl();
        return individualpagedetailUrl;
    }

    public void setInputDetailPath(RichInputText inputDetailPath) {
        this.inputDetailPath = inputDetailPath;
    }

    public RichInputText getInputDetailPath() {
        return inputDetailPath;
    }

    public void setSearchPram(String searchPram) {
        this.searchPram = searchPram;
    }

    public String getSearchPram() {
        //        if(inputTextSearch.getValue()!=null) {
        //            searchPram ="&SearchInput=" + inputTextSearch.getValue().toString();
        //        }
        return searchPram;
    }

    public void setInputTextSearch(RichInputText inputTextSearch) {
        this.inputTextSearch = inputTextSearch;
    }

    public RichInputText getInputTextSearch() {
        return inputTextSearch;
    }

    public void inputSearchTextValueChange(ValueChangeEvent valueChangeEvent) {
        if (inputTextSearch.getValue() != null) {
            searchPram =
                    "?SearchInput=" + inputTextSearch.getValue().toString();
        }
        // Add event code here...
    }

    public void SearchBottonClickListenter(ActionEvent actionEvent) {
        FacesContext context = FacesContext.getCurrentInstance();

        HttpServletRequest request =
            (HttpServletRequest)context.getExternalContext().getRequest();
        request.getContextPath();
        String rootcontext = request.getContextPath();
        String url = rootcontext + searchUrl;
        HttpServletResponse response =
            (HttpServletResponse)context.getCurrentInstance().getExternalContext().getResponse();
        if (inputTextSearch.getValue() != null)
            url += "?SearchInput=" + inputTextSearch.getValue().toString();
        try {
            response.sendRedirect(url);
            context.responseComplete();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void setSearchUrl(String searchUrl) {
        this.searchUrl = searchUrl;
    }

    public String getSearchUrl() {
        return searchUrl;
    }

    public void setInitPram(String initPram) {
        this.initPram = initPram;
    }

    public String getInitPram() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request =
            (HttpServletRequest)context.getExternalContext().getRequest();
        if (txtNoidung.getValue() == null) {
            if (request.getParameter("SearchInput") != null) {
                String inputvalue = request.getParameter("SearchInput");
                txtNoidung.setValue(inputvalue);
                getListNewsByKieutinWithPaging(1);
            }
        }
        return initPram;
    }

    public void setTotalRows(String totalRows) {
        this.totalRows = totalRows;
    }

    public String getTotalRows() {
        return totalRows;
    }
}
